import {observable, action} from 'mobx';
import * as mobx from 'mobx';
import {WeaTools} from 'ecCom';
import {message} from 'antd';
import * as urls from '../constants/ServerUrls';
import SearchFavourite from '../util/SearchFavourite';
import * as treeUtil from '../util/TreeUtil';
import {WeaLocaleProvider} from 'ecCom';
import objectAssign from 'object-assign';

const getLabel = WeaLocaleProvider.getLabel;
const {callApi} = WeaTools;

export default class FavouriteDirStore {
    /** 树节点的数据 */
    @observable treeData = [];
    /** 点击展开节点，默认展开 */
    @observable clickExpanded = true;
    /** 选中的节点 */
    @observable selectedKey = '-1';
    /** 展开的节点 */
    @observable expandedKeys = [];
    /** 鼠标移入的节点 */
    @observable operatingKey = '';
    /** 全部目录(根目录)是否鼠标移入 */
    @observable isover = false;
    @observable curTree = {};
    /**
     * SysFavouriteStore的实例
     */
    @observable initTreeData = [];
    @observable loadedTreeData = [];
    sysFavouriteStore = null;

    /**
     * 添加根目录的按钮是否可用
     * true：不可用
     * false：可用
     */
    addBtnDisable = false;

    constructor(sysFavouriteStore) {
        this.sysFavouriteStore = sysFavouriteStore;
    }

    @action.bound
    controlBtnDisable(val = false) {
        this.addBtnDisable = val;
    }

    @action.bound
    setInitTreeData(data) {
        this.initTreeData = data;
    }

    @action initTree() {
        this.treeData = [];
        this.expandedKeys = [];
        this.selectedKey = '-1';
    }

    /**
     * 加载目录树
     * @param parentId
     * @param resovle
     */
    @action getObjTree = (obj) => {
        this.curTree = obj;
    }
    @action loadTree = (parentId, resovle) => {
        const treeurl = urls.LOAD_TREE_URL;
        callApi(treeurl, 'POST', {parentId}).then((resdata) => {
            const msg = resdata.msg;
            const success = resdata.success;
            if (success == '1') {
                const data = resdata.data;
                this.setTreeData(data, parentId);
                if (resovle) {
                    resovle();
                }
            }
        });
    }

    @action
    loadTreedata = (parentId) => {
        const treeurl = urls.LOAD_TREE_URL;
        return new Promise((resovle, reject) => {
            callApi(treeurl, 'POST', {parentId}).then((resdata) => {
                const success = resdata.success;
                if (success == '1') {
                    const data = resdata.data;
                    const newdata = [];
                    /**
                     * 设置树节点的数据
                     */
                    data.map((val, index) => {
                        newdata.push({
                            nodeid: val.favid,
                            canClick: true, // 标识节点是否可以点击 （单选 多选模式下生效）
                            icon: val.child == 1 ? 'icon-coms-LargeArea' : '', // 图标展示
                            isParent: val.child == 1, // 父节点标识
                            name: val.favname, // 名称
                            dragDisabled: val.favid == '-1', // 禁止节点拖拽
                            ops: val.favid == -1 ? [] : [
                                {type: 'edit'},
                                {type: 'add'},
                                {type: val.child == 1 ? '' : 'delete'},
                            ],
                        });
                    });

                    if (parentId == 0) {
                        this.initTreeData = newdata;
                    } else {
                        this.loadedTreeData = newdata;
                    }
                    resovle(this.initTreeData);
                }
            });
        });
    }

    @action
    addDirectory = (parentid, favname) => {
        const favurl = urls.ADD_FAVOURITE_DIR;
        return new Promise((resolve) => {
            callApi(favurl, 'POST', {parentid, favname}).then((resdata) => {
                const success = resdata.success;
                if (success == 1) {
                    const newdata = [];
                    newdata.push({
                        nodeid: resdata.id,
                        canClick: true, // 标识节点是否可以点击 （单选 多选模式下生效）
                        icon: '', // 图标展示
                        isParent: false, // 父节点标识
                        name: favname, // 名称
                        dragDisabled: true, // 禁止节点拖拽
                        ops: [
                            {type: 'edit'},
                            {type: 'add'},
                            {type: 'delete'},
                        ],

                    });
                    resolve(newdata[0]);

                    this.addBtnDisable = false;
                }
            });
        });
    }
    @action
    deleteNode = (favid, callback) => {
        const favurl = urls.DELETE_FAVOURITE_DIR;
        return new Promise((resolve) => {
            callApi(favurl, 'POST', {favid}).then((resdata) => {
                const success = resdata.success;
                if (success == 1) {
                    message.info(`${getLabel(20461, '删除成功')}`);

                    callback && typeof callback == 'function' && callback();
                } else {
                    message.error(resdata.msg);
                }
            });
        });
    }
    @action
    saveDragNode = (dragNode, targetNode, datas) => {
        /*
          let favid = dragNode.nodeid
           let parentid = targetNode.nodeid
           let index = 0
           let islast = true
           let dragParentId =''
           let list = []

           //判定是否是排序
           if(targetNode.dropToGap){
               // 判断parentId
               if(!targetNode.parentTreeKey){
                   parentid='0'
               }else{
                   let arr=targetNode.treeKey.split('__')
                   if(arr.length==3){
                       parentid = arr[0]
                   }else{
                       parentid = arr.slice(arr.length-3,arr.length-2).join().split('-')[1]
                   }

               }
               //判断是不是在根目录下
               if(!targetNode.parentTreeKey){
                   datas.map((val,index)=>{
                       list.push({
                           favid:val.nodeid,parentid,index
                       })
                   })
                   islast=false
               }
               else{
                   let str=targetNode.treeKey
                   let newarr = str.split('__').slice(0,str.split('__').length-1)
                   let ss = newarr.splice(0,1)
                   let ssd =newarr.map((val)=>{return val.split('-')[1]})
                   let parentArr=[...ss,...ssd]
                   parentArr.pop()
                   var result = []
                   function find(datas){
                   var target = parentArr.shift()
                       if(target){
                           result = datas.find((value)=>{return(value.nodeid==target)})
                           find(result.children)
                       }else{
                           return(result)
                       }
                   }
                   find(datas)
                   if(result!=false){
                       result.children.map((val,index)=>{
                           list.push({
                               favid:val.nodeid,parentid,index
                           })
                       })
                       islast=false
                   }
               }


           }else{
               list.push({favid,parentid,index:'0'})

           }


           let node = {}
           node={"favname":dragNode.name,"favorder":"1","readchild":"0","favdesc":"","favid":dragNode.nodeid,"parentid":parentid,"child":"0","isover":false,"children":[]}

           let arr=dragNode.treeKey.split('__')
           if(arr.length==3|2){
               dragParentId = arr[0]
           }else{
               dragParentId = arr.slice(arr.length-3,arr.length-2).join().split('-')[1]
           }

           list = JSON.stringify(list);
           node = JSON.stringify(node)
           let saveurl = urls.SAVE_FAVOURITE_DIR;
           return new Promise((resolve)=>{
               callApi(saveurl, "POST", {list, node, islast, dragParentId}).then(data => {
               })
           })
           */

        let islast = false;
        const dragParentId = '0';
        let list = [];
        let node = [];

        /**
         * 根据节点id获取到节点的信息
         * @param treeData
         * @param nodeKey
         */
        const getNodeData = (treeData, nodeKey) => {
            const loop = (data, key, ndata) => {
                for (let i = 0; i < data.length; i++) {
                    const item = data[i];
                    const {nodeid, children = []} = item;
                    if (nodeid == key) {
                        objectAssign(ndata, {...item});
                        return;
                    }
                    if (children.length > 0) {
                        loop(children, key, ndata);
                    }
                }
            };

            const nodeData = {};
            loop(treeData, nodeKey, nodeData);
            return nodeData;
        };

        let parentid = '0';
        const nodeInfo = getNodeData(datas, dragNode.nodeid);
        if (nodeInfo) {
            const {treeKey} = nodeInfo;
            if (treeKey) {
                let parentTreeKey = '';
                const arr = treeKey.split('-');
                if (arr.length == 2) { // 说明有父节点
                    parentTreeKey = arr[0];
                    const parentArr = parentTreeKey.split('__');
                    if (parentArr.length == 2) {
                        parentid = parentArr[0];
                    }
                    node = {favid: dragNode.nodeid, parentid};

                    let parentNode = null;

                    if (parentid == targetNode.nodeid) { // 说明是拖动到目标节点下
                        if ((targetNode.isParent || targetNode.haschild) && targetNode.isLoad) { // 已经父节点数据已加载，那么也是排序
                            parentNode = getNodeData(datas, parentid);
                        } else {
                            // 父节点还未展开，那么就只能插入到父节点的所有节点之后
                            islast = true;
                        }
                    } else { // 跟目标节点平级，那么就是排序
                        parentNode = getNodeData(datas, parentid);
                    }

                    if (parentNode && parentNode.children) {
                        const {children = []} = parentNode;
                        children.map((val, index) => {
                            list.push({favid: val.nodeid, parentid, index});
                        });
                    }
                } else if (arr.length == 1) { // 说明是拖动到根节点
                    node = {favid: dragNode.nodeid, parentid};
                    datas.map((val, index) => {
                        list.push({favid: val.nodeid, parentid, index});
                    });
                }
            }

            node = JSON.stringify(node);
            list = JSON.stringify(list);

            const params = {node, list, islast, dragParentId};
            const saveurl = urls.SAVE_FAVOURITE_DIR;

            callApi(saveurl, 'POST', params).then((data) => {
            });
        }
    }

    @action
    editDirectory = (value, node) => {
        let arr = [];
        let parentid = '';
        const favid = node.nodeid;
        const favname = value;
        const favurl = urls.EDIT_FAVOURITE_DIR;


        if (!node.parentTreeKey) {
            parentid = '0';
        } else {
            arr = node.treeKey.split('__');
            if (arr.length == 3) {
                parentid = arr[0];
            } else {
                parentid = arr.slice(arr.length - 3, arr.length - 2).join().split('-')[1];
            }
        }
        return new Promise((resolve) => {
            callApi(favurl, 'POST', {parentid, favid, favname}).then((resdata) => {
                const success = resdata.success;
                if (success == 1) {
                    const newdata = [];
                    newdata.push({
                        nodeid: resdata.id,
                        canClick: true, // 标识节点是否可以点击 （单选 多选模式下生效）
                        icon: '', // 图标展示
                        isParent: false, // 父节点标识
                        name: favname, // 名称
                        dragDisabled: true, // 禁止节点拖拽
                        ops: favid == -1 ? [] : [
                            {type: 'edit'},
                            {type: 'add'},
                        ],

                    });
                    resolve(newdata[0]);
                }
            });
        });
    }
    /**
     * 加载一个节点的数据，并展开这个节点
     * @param parentId
     * @param resovlehandle
     */
    @action loadAndExpand = (parentId, resovle) => {
        const treeurl = urls.LOAD_TREE_URL;
        callApi(treeurl, 'POST', {parentId}).then((resdata) => {
            const msg = resdata.msg;
            const success = resdata.success;
            if (success == '1') {
                const data = resdata.data;
                this.setTreeData(data, parentId);
                this.expandTreeNode([parentId], true);
                if (resovle) {
                    resovle();
                }
            }
        });
    }

    /**
     * 节点选中
     * @param selectedKey
     */
    @action selectTreeNode = (selectedKey) => {
        this.selectedKey = selectedKey;
    }

    /**
     * 展开节点
     * @param expandedKeyArr
     * @param expanded
     */
    @action expandTreeNode = (expandedKeyArr, expanded) => {
        let expandedKeys = mobx.toJS(this.expandedKeys);
        expandedKeyArr.forEach((expandedKey) => {
            if (expanded) { // 展开
                if (expandedKeys.indexOf(expandedKey) == -1) {
                    expandedKeys.push(expandedKey);
                }
            } else { // 收缩loadAndExpand
                const tempIds = [];
                if (expandedKeys.indexOf(expandedKey) != -1) {
                    expandedKeys.forEach((eid) => {
                        if (eid != expandedKey) {
                            tempIds.push(eid);
                        }
                    });
                }
                expandedKeys = [...tempIds];
            }
        });

        this.expandedKeys = [...expandedKeys];
    }
    /**
     * 添加树节点
     * @param selectedKey
     */
    @action addTreeNode = (selectedKey) => {
        const treeData = mobx.toJS(this.treeData);
        const newData = treeUtil.getAddTreeData(treeData, selectedKey);
        this.treeData = newData;
    }

    /**
     * 编辑树节点
     * @param nodeKey
     */
    @action editTreeNode = (nodeKey) => {
        const treeData = mobx.toJS(this.treeData);
        const newData = treeUtil.getEditTreeData(treeData, nodeKey);
        this.treeData = newData;
    }

    /**
     * 保存新增的树节点
     * @param params
     * @param resovle
     */
    @action saveAddTreeNode = (params, resovle) => {
        const favurl = urls.ADD_FAVOURITE_DIR;
        const {parentid} = params;

        callApi(favurl, 'POST', {...params}).then((resdata) => {
            const success = resdata.success;
            let msg = '';
            if (success == '0') {
                msg = resdata.msg;
                if (msg) {
                    message.error(msg);
                }
            }

            this.loadTree(parentid, resovle); // 刷新父节点下的所有节点
        });
    }


    /**
     * 保存编辑的树节点
     * @param params
     * @param resovle
     */
    @action saveEditTreeNode = (params, resovle) => {
        const favurl = urls.EDIT_FAVOURITE_DIR;
        const {parentid, favname, favid} = params;

        callApi(favurl, 'POST', {...params}).then((resdata) => {
            const success = resdata.success;
            let msg = '';

            let isinput = false;
            if (success == '0') {
                msg = resdata.msg;
                isinput = true;
                if (msg) {
                    message.error(msg);
                }
            }

            this.updateTreeNodeData(favid, {favname, isinput});
            this.setClickExpanded(true);
        });
    }

    /**
     * 删除树节点
     * @param favid
     */
    @action deleteTreeNode = (favid) => {
        const favurl = urls.DELETE_FAVOURITE_DIR;

        callApi(favurl, 'POST', {favid}).then((resdata) => {
            const success = resdata.success;
            let msg = '';
            if (success == '0') {
                msg = resdata.msg;

                if (msg) {
                    message.error(msg);
                }
            } else {
                const nodeId = '-1';
                this.selectTreeNode(nodeId); // 默认选中“我的收藏”

                /**
                 * 选中树节点后，刷新收藏的列表
                 */
                const isinit = true;
                const isreload = false;
                SearchFavourite.setConditions({dirId: nodeId});
                const searchFavourite = new SearchFavourite(this.sysFavouriteStore);
                searchFavourite.load({isinit, isreload});

                /**
                 * 刷新父节点
                 */
                const {parent} = resdata;
                const parentId = parent.favid; // 父节点id
                this.loadTree(parentId); // 重新加载父节点下的所有子节点
                this.updateTreeNodeData(parentId, parent);
            }
        });
    }

    /**
     * 拖动节点
     * @param dragKey
     * @param dropKey
     * @param dropPos
     * @param dropToGap
     */
    @action handleDragNode = (dragKey, dropKey, dropPos, dropToGap) => {
        const treeData = mobx.toJS(this.treeData);
        const ndata = jQuery.extend(true, [], treeData); // 深度copy数据
        const dragInfo = {dragKey, dropKey, dropPos, dropToGap};
        const handleResult = treeUtil.handleDragNodeData(ndata, dragInfo);
        let {list, node, dragParentId, dropParentId, islast} = handleResult;
        // 树数据更新
        this.treeData = handleResult.treeData;

        // 展开节点
        this.expandTreeNode([dropKey], true);

        /**
         * 异步请求，保存数据到服务器端
         */
        list = jQuery.extend(true, [], list); // 深度copy数据
        list = list.map((item, index) => {
            const {favid, parentid} = item;
            return {favid, parentid, index};
        });

        list = JSON.stringify(list);
        node = JSON.stringify(node);
        const saveurl = urls.SAVE_FAVOURITE_DIR;
        callApi(saveurl, 'POST', {list, node, islast, dragParentId}).then((resdata) => {
            const success = resdata.success;
            let msg = '';
            if (success == '0') {
                msg = resdata.msg;
                if (msg) {
                    message.error(msg);
                }
            } else {
                /**
                 * 刷新拖动节点的父节点，因为拖动后，可能就没有子节点了
                 */
                const {parent} = resdata;
                const parentId = parent.favid; // 父节点id
                this.updateTreeNodeData(parentId, parent); // 更新父节点的信息
            }
        });
    }


    /**
     * 更新树节点信息
     * @param nodeKey
     * @param params
     */
    @action updateTreeNodeData = (nodeKey, params) => {
        const treeData = mobx.toJS(this.treeData);
        const newData = treeUtil.updateNodeData(treeData, nodeKey, params);
        this.treeData = newData;
    }

    /**
     * 根目录（全部目录）鼠标移入、移出状态设置
     * @param isover
     */
    @action setRootOver = (isover) => {
        this.isover = isover;
    }
    lo
    /**
     * 根目录（全部目录）选中状态设置
     */
    @action setRootClick = () => {
        this.selectedKey = '0';
    }

    /**
     * 设置，点击时，是否展开节点
     * @param expanded
     */
    @action setClickExpanded = (expanded) => {
        this.clickExpanded = expanded;
    }

    /**
     * 鼠标移动到节点上，显示编辑、删除操作按钮
     * @param nodeKey
     * @param isover
     */
    @action toggleNodeOperation = (nodeKey, isover) => {
        const treeData = mobx.toJS(this.treeData);
        const newData = treeUtil.getOverTreeData(treeData, nodeKey, isover);
        if (isover) {
            this.operatingKey = nodeKey;
        } else {
            this.operatingKey = '';
        }
        this.treeData = newData;
    }

    /**
     * 获取节点信息
     * @param nodeKey
     * @returns {{}}
     */
    @action getNodeInfo = (nodeKey) => {
        const treeData = mobx.toJS(this.treeData);
        const ndata = treeUtil.getNodeData(treeData, nodeKey);
        return ndata;
    }

    setTreeData = (data, parentId) => {
        const treeData = mobx.toJS(this.treeData);
        const newData = treeUtil.getNewTreeData(treeData, parentId, data);
        this.treeData = newData;
    }
}
